//引入express模块
const express = require("express");
//引入数据库连接模块
const pool = require("../pool.js");
//引入公用函数
const xsp_fn = require("../others/xsp_fn");
//创建路由器对象
const mR = express.Router();
//以下为接口部分

//地址添加接口
//接口地址：http://127.0.0.1:3000/address/add
//接口方式：post
mR.post("/add", (req, res, next) => {
  let c_add = xsp_fn.api_add("user_address");
  pool.query(c_add.sql, [req.body], (err, data) => {
    if (err) {
      res.send(c_add.err);
      next(err);
    } else {
      console.log(data);
      res.send(c_add.success);
    }
  });
});

//删除地址接口
//接口地址：http://127.0.0.1:3000/address/delete
//接口方式：delete
mR.delete("/delete", (req, res, next) => {
  let c_delete = `delete from user_address where id=?`;
  pool.query(c_delete, [req.query.id], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    if (data.changedRows) {
      res.send({ code: 0, msg: "删除失败" });
    } else {
      res.send({ code: 1, msg: "删除成功" });
    }
  });
});

//修改地址接口
//接口地址：http://127.0.0.1:3000/address/update
//接口方式：put
mR.put("/update", (req, res, next) => {
    let c_update = xsp_fn.api_update("user_address");
    pool.query(c_update.sql, [req.body, req.body.id], (err, data) => {
        if (err) {
            next(err);
            return;
        }
        if (data.changedRows) {
            res.send(c_update.success);
        } else {
            res.send(c_update.err);
        }
    });
});
//查看用户地址信息
//接口地址：http://127.0.0.1:3000/address/userinfo
//接口方式：get
mR.get("/userinfo", (req, res, next) => {
    // console.log(req.query.uid);
    pool.query(
      "select * from user_address where user_id=?",
      [req.query.user_id],
      (err, data) => {
        if (err) {
          console.log(err);
          next(err);
          return;
        }
        res.send({ code: 1, msg: "查询成功", data });
      }
    );
  });
//暴露出去
module.exports = mR;
